//% color="#4169E1" iconWidth=50 iconHeight=40
namespace OneNet{
    //% block="OneNet Init Server [IP]Device ID [DID]Product ID [PID]ApiKey [API]" blockType="command" 
    //% IP.shadow="string" IP.defl="183.230.40.39"
    //% DID.shadow="string" DID.defl="593516433"
    //% PID.shadow="string" PID.defl="339686"
    //% API.shadow="string" API.defl="your_private_key"
   
    export function OneNetInit(parameter: any, block: any) {
         let ip = parameter.IP.code;  
         let did = parameter.DID.code;
         let pid = parameter.PID.code;
         let api = parameter.API.code;

         ip = replace(ip);
         did = replace(did);
         pid = replace(pid);
         api = replace(api);

         
        Generator.addImport("from mpython import *");
        Generator.addImport("from umqtt.simple import MQTTClient");
        Generator.addImport("from machine import Timer");
        Generator.addImport("import machine");
        Generator.addImport("import ubinascii");

        Generator.addDeclaration("OneNET_recv","def OneNET_recv(_msg):pass\n_OneNET_msg_list = []")

        Generator.addDeclaration("callback","def OneNET_callback(_topic, _msg):\n\t\tglobal _OneNET_msg_list\n\t\ttry: _msg = _msg.decode('utf-8', 'ignore')\n\t\texcept: print(_msg);return\n\t\tOneNET_recv(_msg)\n\t\tif _msg in _OneNET_msg_list:\n\t\t\t\teval('OneNET_recv_' + bytes.decode(ubinascii.hexlify(_msg)) + '()')\n\ntim14 = Timer(14)");
   
        Generator.addDeclaration("tick","\n_iot_count = 0\ndef timer14_tick(_):\n\t\tglobal _iot, _iot_count\n\t\t_iot_count = _iot_count + 1\n\t\tif _iot_count == 1000: _iot.ping(); _iot_count = 0\n\t\ttry: _iot.check_msg()\n\t\texcept: machine.reset()")

        Generator.addDeclaration("setup",`\n_iot = None\ndef OneNET_setup():\n\t\tglobal _iot\n\t\t_iot = MQTTClient('${did}', '${ip}', 6002, '${pid}', '${api}', keepalive=300)\n\t\t_iot.set_callback(OneNET_callback)\n\t\tif 1 == _iot.connect(): print('Successfully connected to MQTT server.')\n\t\ttim14.init(period=200, mode=Timer.PERIODIC, callback=timer14_tick) `)
        Generator.addCode("OneNET_setup()");
        
    }
    //% block="OneNetReceive  Mess  " blockType="hat"    
    export function OneNetReceive(parameter: any, block: any) {
        
        Generator.addImport("import time");
        
        Generator.addDeclaration("mess","global  mess");
        Generator.addEvent("OneNetReceive","OneNET_recv",`_msg`);

        Generator.addCode(`mess=_msg `);
       

        
   }
    //% block="OneNetSpecificReceive  Mess  " blockType="reporter"  
    export function OneNetSpecificReceive(parameter: any, block: any) {
          
        Generator.addCode(`mess`);
        
    }
    //% block="OneNetsend data name [NAME]value [VALUE]   " blockType="command" 
    //% NAME.shadow="string" NAME.defl="light"  
    //% VALUE.shadow="string" DAY.defl=""
    
    export function OneNetsend_data(parameter: any, block: any) {
        let name = parameter.NAME.code; 
        let value = parameter.VALUE.code;  
        Generator.addImport("import json");

        Generator.addDeclaration("pubdata","def pubdata(_dic):\n\t\tprint(_dic)\n\t\t_list = []\n\t\tfor _key in list(_dic.keys()):\n\t\t\t\t_d = {'id':_key,'datapoints':[{'value':_dic[_key]}]}\n\t\t\t\t_list.append(_d)\n\t\t_data = {'datastreams': _list}\n\t\tj_d = json.dumps(_data)\n\t\tj_l = len(j_d)\n\t\tarr = bytearray(j_l + 3)\n\t\tarr[0] = 1\n\t\tarr[1] = int(j_l / 256)\n\t\tarr[2] = j_l % 256\n\t\tarr[3:] = j_d.encode('ascii')\n\t\treturn arr");


        Generator.addCode(`_iot.publish('$dp', pubdata({'${name}':${value}}))`,false);
          
   }
    //% block="OneNetsend_dataList  Mess[MESS]   " blockType="command" 
    //% MESS.shadow="string" MESS.defl="hello"  
       
    export function OneNetsend_dataList(parameter: any, block: any) {
        let mess = parameter.MESS.code; 
                
        Generator.addDeclaration("pubdata","def pubdata(_dic):\n\t\tprint(_dic)\n\t\t_list = []\n\t\tfor _key in list(_dic.keys()):\n\t\t\t\t_d = {'id':_key,'datapoints':[{'value':_dic[_key]}]}\n\t\t\t\t_list.append(_d)\n\t\t_data = {'datastreams': _list}\n\t\tj_d = json.dumps(_data)\n\t\tj_l = len(j_d)\n\t\tarr = bytearray(j_l + 3)\n\t\tarr[0] = 1\n\t\tarr[1] = int(j_l / 256)\n\t\tarr[2] = j_l % 256\n\t\tarr[3:] = j_d.encode('ascii')\n\t\treturn arr",true);
        Generator.addCode(`_iot.publish('$dp', pubdata(${mess}))`,false);          
   }

       //% block="OneNetDisconnect   " blockType="command" 
       export function OneNetDisconnect(parameter: any, block: any) { 
        Generator.addCode(`tim14.deinit()`);
        Generator.addCode(`_iot.disconnect()`);
        
        Generator.addCode(`_print('Disconnected from MQTT server.')`);
        
 }
   function replace(str :string) {
    return str.replace("\"", "").replace("\"", "");
}
}
    